/*
 */
package de.aurelius.transaction;

import java.util.HashMap;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

/**
 *
 */
public class EmployeeDaoImpl implements EmployeeDao {

    private final DataSource dataSource;
    private static final String INSERT_STATEMENT =
            "insert into employees(identifier, username, value) values (:id,:name, :value)";

    public EmployeeDaoImpl(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public void executeQuery(int id, String name, int value) {
        NamedParameterJdbcTemplate namedParameterJdbcTemplate =
                new NamedParameterJdbcTemplate(dataSource);

        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("id", id);
        map.put("name", name);
        map.put("value", value);
        namedParameterJdbcTemplate.update(INSERT_STATEMENT, map);
    }

    @Override
    public void createTable() {

        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        jdbcTemplate.update("CREATE TABLE employees\n"
                + "(identifier NUMERIC(4) CONSTRAINT PK_PRAC PRIMARY KEY,\n"
                + "username CHARACTER VARYING(15),\n"
                + "value NUMERIC(5));");

    }

    @Override
    public void dropTable() {

        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        jdbcTemplate.update("drop TABLE employees");

    }

    @Override
    public int countEmployees() {

        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        return jdbcTemplate.queryForInt("select count(*) from employees");

    }
}
